export class Bus {
  private static _instance: Bus
  public _listeners: Map<string, Array<(...args: unknown[]) => unknown>> = new Map()
  public CHANGE_ROUTE = 'change-route'
  public constructor () {
    this._listeners = new Map()
  }

  public static get instance (): Bus {
    if (!Bus._instance) {
      Bus._instance = new Bus()
    }
    return Bus._instance
  }

  on (event: string, listener: (...args: unknown[]) => unknown) {
    if (!this._listeners.has(event)) {
      this._listeners.set(event, [])
    }
    const listeners = this._listeners.get(event)
    listeners?.push(listener)
    this._listeners.set(event, listeners ?? [])
  }

  emit (event: string, ...args: unknown[]) {
    if (this._listeners.has(event)) {
      this._listeners.get(event)?.forEach(listener => listener(...args))
    }
  }
}

export default Bus
